package dnl.toolbox.lang;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ThreadUtils {

	public static void sleepQuitely(long millis) {
		try {
			Thread.sleep(millis);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static ThreadGroup getRootThreadGroup() {
		ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
		ThreadGroup parentGroup;
		while ((parentGroup = rootGroup.getParent()) != null) {
			rootGroup = parentGroup;
		}
		return rootGroup;
	}

	public static Set<Thread> getAllThreads() {
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		return threadSet;
	}

	public static Set<Thread> getAllThreadsInGroup(String threadGroup) {
		Set<Thread> result = new HashSet<Thread>(); 
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		for (Thread thread : threadSet) {
			if(thread.getThreadGroup().getName().equals(threadGroup)){
				result.add(thread);
			}
		}
		return result;
	}

	public static Map<String, List<Thread>> getThreadsByGroups(String threadGroupPrefix) {
		Map<String, List<Thread>> result = new HashMap<String, List<Thread>>(); 
		Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
		for (Thread thread : threadSet) {
			if(thread.getThreadGroup().getName().startsWith(threadGroupPrefix)){
				List<Thread> tl = result.get(thread.getThreadGroup().getName());
				if(tl == null){
					tl = new ArrayList<Thread>();
					result.put(thread.getThreadGroup().getName(), tl);
				}
				tl.add(thread);
			}
		}
		return result;
	}

	public static List<Thread> getThreadsOrderedByGroups(String threadGroupPrefix) {
		List<Thread> threads = new ArrayList<Thread>();
    	Map<String, List<Thread>> threadsByGroup = getThreadsByGroups("VALIRE_");
    	Collection<List<Thread>> values = threadsByGroup.values();
    	for (List<Thread> list : values) {
    		for (Thread thread : list) {
				threads.add(thread);
			}
		}
		return threads;
	}
	
}
